package com.example.sellqq.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.sellqq.constant.ResourceConstant;
import com.example.sellqq.domain.AddressBook;
import com.example.sellqq.domain.Record;
import com.example.sellqq.domain.User;
import com.example.sellqq.exception.APIException;
import com.example.sellqq.repository.AddressBookRepository;
import com.example.sellqq.repository.RecordRepository;
import com.example.sellqq.repository.UserRepository;
import com.example.sellqq.service.UserService;
import com.example.sellqq.util.FileUtils;
import com.example.sellqq.vo.ResponseVO;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @Author: thekernel
 * @Date: 2020/4/20 00:20
 * @Version: 1.0
 * @Description:
 */
@Service(value = "UserService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private RecordRepository recordRepository;

    @Autowired
    private AddressBookRepository addressBookRepository;

    /**
     * 添加卖号信息
     *
     * @param user 卖号信息
     * @return 1: 添加成功 0: 添加失败
     */
    @Override
    public ResponseVO addSellInfo(User user) {
        user.setStatus(Boolean.TRUE);
        user.setCreateTime(new Date());
        User savedUser = this.userRepository.save(user);
        return ResponseVO.success("添加成功", savedUser);
    }

    /**
     * 上传图片
     *
     * @param imageFile 图片文件
     * @return ResponseVO.SUCCESS: 上传成功 ResponseVO.FAIL: 上传失败
     */
    @Override
    public ResponseVO uploadImage(MultipartFile imageFile) throws IOException {
        String imageName = FileUtils.generateRandomFilename() + ".jpg";
        String dataPath = ResourceConstant.ABSOLUTE_IMAGE_PATH + imageName;
        JSONObject returnData = new JSONObject();
        File directory = new File("");//设定为当前文件夹
        imageFile.transferTo(new File(directory.getAbsolutePath(), dataPath));
        returnData.put("url", imageName);
        return ResponseVO.success("上传成功", returnData);
    }

    /**
     * 获取所有卖号信息
     *
     * @return 卖号信息
     */
    @Override
    public ResponseVO getAllSellInfo() {
        List<User> users = this.userRepository.findAll();
        return ResponseVO.success("获取信息成功", users);
    }

    /**
     * 导出为 excel
     *
     * @return excel文件
     */
    @Override
    public HSSFWorkbook exportExcel() {
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 生成一个表格，设置表格名称为"学生表"
        HSSFSheet sheet = workbook.createSheet("出售表");
        // 设置表格列宽度为10个字节
        sheet.setDefaultColumnWidth(10);

        // 创建第一行表头
        HSSFRow headRow = sheet.createRow(0);
        // 表头数据
        String[] header = {"ID", "姓名", "QQ号", "地址", "设备码", "设备类型", "身份证", "身份证正面图片", "身份证背面图片", "手持身份证图片", "创建时间"};
        // 遍历添加表头(下面模拟遍历学生，也是同样的操作过程)
        for (int i = 0; i < header.length; i++) {
            // 创建一个单元格
            HSSFCell cell = headRow.createCell(i);
            // 创建一个内容对象
            HSSFRichTextString text = new HSSFRichTextString(header[i]);
            // 将内容对象的文字内容写入到单元格中
            cell.setCellValue(text);
        }

        List<User> users = this.userRepository.findAll(Sort.by(Sort.Direction.DESC, "createTime"));
        // 内容
        for (int i = 0; i < users.size(); i++) {
            User user = users.get(i);
            HSSFRow row = sheet.createRow(i + 1);
            int j = 0;

            HSSFCell cell = row.createCell(j++);
            HSSFRichTextString text = new HSSFRichTextString(user.getId().toString());
            cell.setCellValue(text);

            cell = row.createCell(j++);
            text = new HSSFRichTextString(user.getName());
            cell.setCellValue(text);

            cell = row.createCell(j++);
            text = new HSSFRichTextString(user.getQq());
            cell.setCellValue(text);

            cell = row.createCell(j++);
            text = new HSSFRichTextString(user.getLocation());
            cell.setCellValue(text);

            cell = row.createCell(j++);
            text = new HSSFRichTextString(user.getDevId());
            cell.setCellValue(text);

            cell = row.createCell(j++);
            text = new HSSFRichTextString(user.getDevModel());
            cell.setCellValue(text);

            cell = row.createCell(j++);
            text = new HSSFRichTextString(user.getIdCard());
            cell.setCellValue(text);

            cell = row.createCell(j++);
            text = new HSSFRichTextString(user.getImageFront());
            cell.setCellValue(text);

            cell = row.createCell(j++);
            text = new HSSFRichTextString(user.getImageBack());
            cell.setCellValue(text);

            cell = row.createCell(j++);
            text = new HSSFRichTextString(user.getImageHand());
            cell.setCellValue(text);

            cell = row.createCell(j);
            text = dealNull(user.getCreateTime());
            cell.setCellValue(text);
        }

        sheet = workbook.createSheet("通话记录表");
        headRow = sheet.createRow(0);
        // 表头数据
        String[] recordHeader = {"ID", "设备码", "通讯录备注", "电话号码", "通话日期", "通话类型", "通话时长", "创建时间"};
        for (int i = 0; i < recordHeader.length; i++) {
            HSSFCell cell = headRow.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(recordHeader[i]);
            cell.setCellValue(text);
        }

        List<Record> records = this.recordRepository.findAll(Sort.by(Sort.Direction.DESC, "createTime"));
        for (int i = 0; i < records.size(); i++) {
            Record record = records.get(i);
            HSSFRow row = sheet.createRow(i + 1);
            int j = 0;

            HSSFCell cell = row.createCell(j++);
            HSSFRichTextString text = new HSSFRichTextString(record.getId().toString());
            cell.setCellValue(text);
            cell = row.createCell(j++);
            text = new HSSFRichTextString(record.getUserId());
            cell.setCellValue(text);
            cell = row.createCell(j++);
            text = new HSSFRichTextString(record.getName());
            cell.setCellValue(text);
            cell = row.createCell(j++);
            text = new HSSFRichTextString(record.getNumber());
            cell.setCellValue(text);
            cell = row.createCell(j++);
            text = dealNull(record.getDate());
            cell.setCellValue(text);
            cell = row.createCell(j++);
            if (record.getType() == null) {
                text = new HSSFRichTextString("未知");
            } else if (record.getType() == 0) {
                text = new HSSFRichTextString("拨入");
            } else if (record.getType() == 1) {
                text = new HSSFRichTextString("拨出");
            } else if (record.getType() == 2) {
                text = new HSSFRichTextString("未接");
            } else {
                text = new HSSFRichTextString("未知");
            }
            cell.setCellValue(text);
            cell = row.createCell(j++);
            text = dealNull(record.getDuration());
            cell.setCellValue(text);
            cell = row.createCell(j);
            text = dealNull(record.getCreateTime());
            cell.setCellValue(text);
        }

        sheet = workbook.createSheet("通讯录表");
        headRow = sheet.createRow(0);
        String[] addressBookHeader = {"ID", "姓名", "备注", "电话号码", "设备码", "创建时间"};
        for (int i = 0; i < addressBookHeader.length; i++) {
            HSSFCell cell = headRow.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(addressBookHeader[i]);
            cell.setCellValue(text);
        }

        List<AddressBook> addressBooks = this.addressBookRepository.findAll(Sort.by(Sort.Direction.DESC, "createTime"));
        for (int i = 0; i < addressBooks.size(); i++) {
            AddressBook addressBook = addressBooks.get(i);
            HSSFRow row = sheet.createRow(i + 1);
            int j = 0;

            HSSFCell cell = row.createCell(j++);
            HSSFRichTextString text = new HSSFRichTextString(addressBook.getId().toString());
            cell.setCellValue(text);
            cell = row.createCell(j++);
            text = new HSSFRichTextString(addressBook.getName());
            cell.setCellValue(text);
            cell = row.createCell(j++);
            text = new HSSFRichTextString(addressBook.getNote());
            cell.setCellValue(text);
            cell = row.createCell(j++);
            text = new HSSFRichTextString(addressBook.getNumber());
            cell.setCellValue(text);
            cell = row.createCell(j++);
            text = new HSSFRichTextString(addressBook.getDevId());
            cell.setCellValue(text);
            cell = row.createCell(j);
            text = dealNull(addressBook.getCreateTime());
            cell.setCellValue(text);
        }

        return workbook;
    }

    /**
     * 删除目录下所有图片
     *
     * @return ResponseVO.SUCCESS: 删除成功 ResponseVO.FAIL: 删除失败
     */
    @Override
    public ResponseVO deleteAllImage() {
        File sourceFile = new File("data/image");

        if (!sourceFile.exists()) {
            throw new APIException("目录不存在");
        } else {
            File[] sourceFiles = sourceFile.listFiles();
            if (null == sourceFiles || sourceFiles.length < 1) {
                throw new APIException("待删除文件夹无文件");
            } else {
                for (File file : sourceFiles) {
                    if (!file.getName().equals("卖.png")) {
                        file.delete();
                    }
                }
            }
        }
        return ResponseVO.success("删除成功");
    }

    private HSSFRichTextString dealNull(Object data) {
        HSSFRichTextString text;
        if (data == null) {
            text = new HSSFRichTextString("未知");
        } else {
            text = new HSSFRichTextString(data.toString());
        }
        return text;
    }
}
